package exercises;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;

/**
 * 输入是一个文本文件，程序要计算文本文件中各单词出现的频率，然后输出stdout
 */
public class CountWords {
    static final String REGEX_CHINESE = "[\u4e00-\u9fa5]";// 中文正则
    public static void main(String[] args) {

        long startTime = System.currentTimeMillis(); // 获取开始时间
        String string = "";
        Map<String, Integer> map = new HashMap<>();
        try {
            //读取文件
            String filePath = "resource/CountWordsLittle.txt";
            FileInputStream fis = new FileInputStream(filePath);
            BufferedReader br = new BufferedReader(new InputStreamReader(fis));
            String temp;
            while((temp = br.readLine()) != null){
                string = string + temp;
            }
            System.out.println(string);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 去除中文
        string = string.replaceAll(REGEX_CHINESE, "").replaceAll("\\d+","");
        // 分割字符串
        StringTokenizer st = new StringTokenizer(string); // 用于切分字符串
        System.out.println(st.nextToken(" "));
        //初始化计数器
        int count;
        //初始化word变量
        String word;
        while (st.hasMoreTokens()) {
            //逗号，问号，句号，感叹号，冒号，双引号，单引号，换行符号
            word = st.nextToken("，。？！+,?.!:\"\"' '\n");
            System.out.println(word);
            if (map.containsKey(word)) {
                // HashMap 保存数据
                count = map.get(word);
                //计数器累加
                map.put(word, count + 1);
            } else {
                map.put(word, 1);
            }
        }


        // 输出结果
        List<Map.Entry<String, Integer>> list = new ArrayList<>(map.entrySet());

        System.out.println("---------------------Words分析结果 ——— 输出结果----------"+list.size());
        for (Map.Entry<String, Integer> entry : list) {
            System.out.println(entry.getKey() + ":" + entry.getValue());
        }

        long endTime = System.currentTimeMillis(); // 获取结束时间
        System.out.println("程序运行时间： " + (endTime - startTime) + "ms");

    }

}